package com.itheima.store.controller;

import com.itheima.store.entity.Cart;
import com.itheima.store.entity.CartItem;
import com.itheima.store.entity.Product;
import com.itheima.store.service.ProductService;
import com.itheima.store.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class CartController {

    @Autowired
    ProductService productService;

    @RequestMapping("cart")
    public Result cart(HttpServletRequest request,String method, String pid, String count){

        if("addCart".equals(method)){

            Product product = productService.getProductById(pid);
            CartItem cartItem = new CartItem();
            cartItem.setProduct(product);
            cartItem.setCount(Integer.parseInt(count));

            Cart cart = (Cart) request.getSession().getAttribute("cart");
            if(cart == null){
                cart = new Cart();
                request.getSession().setAttribute("cart",cart);
            }
            cart.addCart(cartItem);

            return new Result(1,"添加购物车成功");
        }
        if("showCart".equals(method)){
            Cart cart = (Cart)request.getSession().getAttribute("cart");
            if(cart != null){
                return new Result(Result.SUCCESS,"查询成功",cart);
            }else{
                return new Result(Result.FAILS,"查询失败，购物车是空的");
            }
        }
        if ("removeCart".equals(method)){

            // 获取购物车对象
            Cart cart = (Cart)request.getSession().getAttribute("cart");
            // 调用业务方法
            cart.removeCart(pid);
            // 响应JSON
            return new Result(Result.SUCCESS,"移除成功",cart);

        }
        if("clearCart".equals(method)){
            Cart cart = (Cart)request.getSession().getAttribute("cart");
            if(cart != null){
                cart.clearCart();
            }
            return new Result(Result.SUCCESS,"清空成功",cart);
        }
        return null;
    }

}
